home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C06 / Stash2.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.5 KB  |  62 lines

  1. //: C06:Stash2.cpp {O}
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Constructors & destructors
  7. #include "Stash2.h"
  8. #include <iostream>
  9. #include <cassert>
  10. using namespace std;
  11. const int increment = 100;
  12.  
  13. Stash::Stash(int sz) {
  14.   size = sz;
  15.   quantity = 0;
  16.   storage = 0;
  17.   next = 0;
  18. }
  19.  
  20. int Stash::add(void* element) {
  21.   if(next >= quantity) // Enough space left?
  22.     inflate(increment);
  23.   // Copy element into storage,
  24.   // starting at next empty space:
  25.   int startBytes = next * size;
  26.   unsigned char* e = (unsigned char*)element;
  27.   for(int i = 0; i < size; i++)
  28.     storage[startBytes + i] = e[i];
  29.   next++;
  30.   return(next - 1); // Index number
  31. }
  32.  
  33. void* Stash::fetch(int index) {
  34.   assert(0 <= index && index < next);
  35.   // Produce pointer to desired element:
  36.   return &(storage[index * size]);
  37. }
  38.  
  39. int Stash::count() {
  40.   return next; // Number of elements in CStash
  41. }
  42.  
  43. void Stash::inflate(int increase) {
  44.   assert(increase > 0);
  45.   int newQuantity = quantity + increase;
  46.   int newBytes = newQuantity * size;
  47.   int oldBytes = quantity * size;
  48.   unsigned char* b = new unsigned char[newBytes];
  49.   for(int i = 0; i < oldBytes; i++)
  50.     b[i] = storage[i]; // Copy old to new
  51.   delete [](storage); // Old storage
  52.   storage = b; // Point to new memory
  53.   quantity = newQuantity;
  54. }
  55.  
  56. Stash::~Stash() {
  57.   if(storage != 0) {
  58.    cout << "freeing storage" << endl;
  59.    delete []storage;
  60.   }
  61. } ///:~
  62.